import {
  DomEditor,
  IDomEditor,
  SlateRange,
  IButtonMenu
} from '@wangeditor/editor'
import axios from '@/utils/request'

type AttachmentElement = {
  type: 'attachment'
  fileName: string
  link: string
  children: EmptyText[]
}

type EmptyText = {
  text: ''
}

class DownloadFileMenu implements IButtonMenu {
  title: string
  iconSvg: string
  tag: string

  constructor() {
    this.title = '下载' // 自定义菜单标题
    this.iconSvg =
      '<svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M23.9999 29.0001L12 17.0001L19.9999 17.0001L19.9999 6.00011L27.9999 6.00011L27.9999 17.0001L35.9999 17.0001L23.9999 29.0001Z" fill="#9b9b9b" stroke="#9b9b9b" stroke-width="3" stroke-linecap="butt" stroke-linejoin="bevel"/><path d="M42 37L6 37" stroke="#9b9b9b" stroke-width="3" stroke-linecap="butt"/><path d="M34 44H14" stroke="#9b9b9b" stroke-width="3" stroke-linecap="butt"/></svg>'
    this.tag = 'button'
  }

  private getSelectedElem(editor: IDomEditor): AttachmentElement | null {
    const node = DomEditor.getSelectedNodeByType(editor, 'attachment')
    if (node == null) return null
    return node as AttachmentElement
  }

  private preview(editor, url: string, name: string) {
    // 替换url
    const token = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJubmpjZmoiLCJzY29wZSI6WyJiaXpfc3lzIiwiYmlnX3NjcmVlbiIsInNlcnZlciIsImFsbCJdLCJkZXRhaWwiOnsiaWQiOjgzNjkxMzg3Mjg2MzYzNzUwNCwib3JnSWQiOjE1OTI2NDM3NzQsImNvcnBJZCI6bnVsbCwidXNlcm5hbWUiOiJubmpjZmoiLCJyZWFsTmFtZSI6IuWNl-WugeW4guW4guWcuuebkeedo-euoeeQhuWxgCIsInBhc3N3b3JkIjpudWxsLCJlbmFibGVkIjp0cnVlLCJhcmVhSWQiOjQ1MDEwMCwiYXJlYUxldmVsIjoyLCJvcmdUeXBlIjpudWxsLCJvcmdDb2RlIjoiIiwiZm9yZWlnblVzZXJJZCI6bnVsbCwibGV2ZWwiOm51bGwsInBob25lIjoiMTgzNzM4MTY2ODciLCJyb2xlRmxhZyI6MCwidXNlclR5cGUiOjIsInJvbGVDb2RlTGlzdCI6WyJSMDA1Il0sImF1dGhvcml0aWVzIjpbeyJhdXRob3JpdHkiOiJSMDA1In1dLCJhY2NvdW50Tm9uRXhwaXJlZCI6dHJ1ZSwiY3JlZGVudGlhbHNOb25FeHBpcmVkIjp0cnVlLCJhY2NvdW50Tm9uTG9ja2VkIjp0cnVlfSwiZXhwIjoxNjYxNzgwNTI2LCJhdXRob3JpdGllcyI6WyJSMDA1Il0sImp0aSI6ImQyMWYxZTNhLWJiNWMtNDMxZC1iODI0LTc4MTdjZDdhMWMwMSIsImNsaWVudF9pZCI6Im5pcHZ0LWFwcCJ9.UwKREujwIG_9esRoBj5v69y0tTEwfp83BbYzqvApStM`
    axios({
      method: 'get',
      url: `/biz/plan/getAttachmentUrl?${url}&token=${token}`,
      responseType: 'blob'
    })
      .then((res) => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        editor.emit('previewFile', {
          url: window.URL.createObjectURL(blob),
          name: name
        })
      })
      .catch(() => {
        editor.emit('previewFile', false)
      })
  }

  private download(editor, url: string, name: string) {
    // 替换url
    const token = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJubmpjZmoiLCJzY29wZSI6WyJiaXpfc3lzIiwiYmlnX3NjcmVlbiIsInNlcnZlciIsImFsbCJdLCJkZXRhaWwiOnsiaWQiOjgzNjkxMzg3Mjg2MzYzNzUwNCwib3JnSWQiOjE1OTI2NDM3NzQsImNvcnBJZCI6bnVsbCwidXNlcm5hbWUiOiJubmpjZmoiLCJyZWFsTmFtZSI6IuWNl-WugeW4guW4guWcuuebkeedo-euoeeQhuWxgCIsInBhc3N3b3JkIjpudWxsLCJlbmFibGVkIjp0cnVlLCJhcmVhSWQiOjQ1MDEwMCwiYXJlYUxldmVsIjoyLCJvcmdUeXBlIjpudWxsLCJvcmdDb2RlIjoiIiwiZm9yZWlnblVzZXJJZCI6bnVsbCwibGV2ZWwiOm51bGwsInBob25lIjoiMTgzNzM4MTY2ODciLCJyb2xlRmxhZyI6MCwidXNlclR5cGUiOjIsInJvbGVDb2RlTGlzdCI6WyJSMDA1Il0sImF1dGhvcml0aWVzIjpbeyJhdXRob3JpdHkiOiJSMDA1In1dLCJhY2NvdW50Tm9uRXhwaXJlZCI6dHJ1ZSwiY3JlZGVudGlhbHNOb25FeHBpcmVkIjp0cnVlLCJhY2NvdW50Tm9uTG9ja2VkIjp0cnVlfSwiZXhwIjoxNjYxNzgwNTI2LCJhdXRob3JpdGllcyI6WyJSMDA1Il0sImp0aSI6ImQyMWYxZTNhLWJiNWMtNDMxZC1iODI0LTc4MTdjZDdhMWMwMSIsImNsaWVudF9pZCI6Im5pcHZ0LWFwcCJ9.UwKREujwIG_9esRoBj5v69y0tTEwfp83BbYzqvApStM`
    axios({
      method: 'get',
      url: `/biz/plan/getAttachmentUrl?${url}&token=${token}`,
      responseType: 'blob'
    })
      .then((res) => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        const a = document.createElement('a')
        a.href = window.URL.createObjectURL(blob)
        a.download = name
        a.click()
        a.remove()
        editor.emit('downloadFile', true)
      })
      .catch(() => {
        editor.emit('downloadFile', false)
      })
  }

  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {
    const attachmentElem = this.getSelectedElem(editor)
    console.log(attachmentElem)

    if (attachmentElem == null) return ''
    return (
      attachmentElem.link.split('pdfPath=')[1] + ',' + attachmentElem.fileName
    )
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {
    return false
  }

  exec(editor: IDomEditor, value: string | boolean) {
    if (!value) return
    if (typeof value !== 'string') return
    this.download(editor, value.split(',')[0], value.split(',')[1])
  }

  isDisabled(editor: IDomEditor): boolean {
    const { selection } = editor
    if (selection == null) return true
    if (SlateRange.isExpanded(selection)) return true // 选区非折叠，禁用

    // 未匹配到 attachment node 则禁用
    const attachmentElem = this.getSelectedElem(editor)
    if (attachmentElem == null) return true

    return false
  }
}

const downloadFileMenuConf = {
  key: 'downloadFile', // 定义 menu key
  factory() {
    return new DownloadFileMenu()
  }
}

export default downloadFileMenuConf
